﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Net;
using System.Windows.Media.Imaging;
using TestTreeView.Model;
using MSSClient.Model;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using OpenCvSharp;
using System.Windows.Controls;
using System.Collections;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Diagnostics;
using System.Reflection;
using NotificationDemoWPF;
using System.Xml;
using System.Runtime.InteropServices;
using PrintDemo;

namespace MSSClient.Utils
{
    /// <summary>
    /// 工具类
    /// </summary>
    class CommonUtil
    {
        #region 变量
        private static PrintDocument fPrintDocument = new PrintDocument();
        public static List<NotificationWindow> _dialogs = new List<NotificationWindow>();
        //报账单条码类型
        static string[] bizType = { "ZF", "BM", "QM", "GF", "SP", "JK", "BH", "RG", "ZS", "YS", "DD", "TY", "TZ", "RF", "ZM", "SF", "XH", "TP" };
        //发票条码类型
        static string[] FPType = { "FP" };
        //承诺函条码类型
        static string[] CNType = { "CN" };
        //写日志的锁
        static Object writerLogLocker = new Object();
        #endregion

        /// <summary>
        /// 弹出消息框
        /// </summary>
        /// <param name="content">需要显示的内容</param>
        public static void ShowMsgFrom(String content)
        {
            NotifyData data = new NotifyData();
            data.Title = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            data.Content = content;

            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                NotificationWindow dialog = new NotificationWindow();//new 一个通知
                dialog.Closed += Dialog_Closed;
                dialog.TopFrom = GetTopFrom();
                _dialogs.Add(dialog);
                dialog.DataContext = data;//设置通知里要显示的数据
                dialog.Show();
            }));
        }
        private static void Dialog_Closed(object sender, EventArgs e)
        {
            var closedDialog = sender as NotificationWindow;
            _dialogs.Remove(closedDialog);
        }

        private static double GetTopFrom()
        {
            //屏幕的高度-底部TaskBar的高度。
            double topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 1;
            bool isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);

            while (isContinueFind)
            {
                topFrom = topFrom - 140;//此处100是NotifyWindow的高 110-100剩下的10  是通知之间的间距
                isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);
            }

            if (topFrom <= 0)
                topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 1;

            return topFrom;
        }

        //在这里写打印的内容
        public static void printDemo()
        {
            //Bahnschrift.ttf
            //Verdana
            //Arial.ttf
            //Calibri.ttf
            PrintService printService = new PrintService();
            //printService.StartPrint(new Bitmap(@"C:\MssClientCache\barcodeCache\t20181206155500555.bmp"), "image");
            //printService.StartPrint(BarPrinter.Convert("TYA20034000000081811001009TY1-FDY1", "sdjhfksajd"), "image");
            String fileName1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".bmp";
            String fileName2 = "t" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".bmp";
            String fileName3 = "tt" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".bmp";
            String fileName4 = "ttt" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".bmp";
            //BarPrinter.Convert("TYA20034000000081811001009TY1-FDY1", fileName1, "Bahnschrift");
            BarPrinter.Convert("TYA20034000000081811001009TY1-FDY1", fileName2, "Verdana");
            //BarPrinter.Convert("TYA20034000000081811001009TY1-FDY1", fileName3, "Calibri");
            //BarPrinter.Convert("TYA20034000000081811001009TY1-FDY1", fileName4, "Arial");

            //printService.StartPrint(new Bitmap(@"C:\MssClientCache\barcodeCache\" + fileName1), "image");
            printService.StartPrint(new Bitmap(@"C:\MssClientCache\barcodeCache\" + fileName2), "image");
            //printService.StartPrint(new Bitmap(@"C:\MssClientCache\barcodeCache\" + fileName3), "image");
            //printService.StartPrint(new Bitmap(@"C:\MssClientCache\barcodeCache\" + fileName4), "image");
            //CommonUtil.PrintTest_Cmd("C://MssClientCache//barcodeCache//" + fileName1);
            //CommonUtil.PrintTest_Cmd("C://MssClientCache//barcodeCache//" + fileName2);
            //CommonUtil.PrintTest_Cmd("C://MssClientCache//barcodeCache//" + fileName3);
            //CommonUtil.PrintTest_Cmd("C://MssClientCache//barcodeCache//" + fileName4);
            //CommonUtil.printBarcode();
        }

        /// <summary> 
        /// 获取正在运行的实例，没有运行的实例返回null; 
        /// </summary> 
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary> 
        /// 获取正在运行的实例，没有运行的实例返回null; 
        /// </summary> 
        public static Process RunningInstance2()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id == current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        #region winscp
        /// <summary>
        /// winScp使用测试方法
        /// 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fileList"></param>
        //public static int testWinScp(Session session,String remotePath,String localPath,String fileName)
        //{
        //    int tag = 0;
        //    try
        //    {
        //        if (session.Opened)
        //        {
        //            // Upload files
        //            TransferOptions transferOptions = new TransferOptions();
        //            transferOptions.TransferMode = TransferMode.Binary;
        //            TransferOperationResult transferResult = null;
        //            if (!session.FileExists(remotePath))
        //                session.CreateDirectory(remotePath);

        //            transferResult = session.PutFiles(localPath, remotePath + "/" + fileName, false, transferOptions);

        //            // Throw on any error
        //            transferResult.Check();

        //            //Print results
        //            if (transferResult.Transfers.Count < 1)
        //            {
        //                //CommonUtil.WriteFtpLog("testWinScp", "");
        //            }
        //            else
        //            {
        //                foreach (TransferEventArgs transfer in transferResult.Transfers)
        //                {
        //                    CommonUtil.WriteFtpLog("testWinScp", transfer.Destination);
        //                }
        //            }
        //            tag = 1;
        //            //session.Close();
        //        }
        //        else
        //            tag = 0;
        //    }
        //    catch (Exception ex)
        //    {
        //        tag = 0;
        //        CommonUtil.WriteLog(ex);
        //    }
        //    return tag;
        //}

        //public static Session getWinScpSession(string ftpIp, string ftpUserName, string ftpPassword, int ftpPort, FtpMode ftpMode)
        //{
        //    Session session = new Session();
        //    try
        //    {
        //        SessionOptions sessionOptions = new SessionOptions
        //        {
        //            Protocol = Protocol.Ftp,
        //            HostName = ftpIp,
        //            UserName = ftpUserName,
        //            Password = ftpPassword,
        //            FtpMode = ftpMode,
        //            PortNumber = ftpPort
        //        };
        //        session.Open(sessionOptions);
        //    }
        //    catch(Exception ex)
        //    {
        //        WriteLog(ex);
        //    }
        //    return session;
        //}
        /// <summary>
        /// 过滤识别的条码：针对报账单和发票
        /// </summary>
        /// <param name="imageCode"></param>
        /// <param name="checkType"></param>
        /// <returns></returns>
        #endregion


        public static bool bizTypeCheck(string imageCode, string checkType)
        {
            #region
            try
            {
                if (imageCode.Length < 2)
                    return false;
                string headCode = imageCode.Substring(0, 2);//截取条码前两位
                if (checkType.Equals("1"))//报账单
                {
                    //if (imageCode.Length != 29)
                    //    return false;
                    if (bizType.Contains(headCode))
                        return true;
                    else
                        return false;
                }
                else if (checkType.Equals("2"))//发票
                {
                    if (FPType.Contains(headCode))
                        return true;
                    else
                        return false;
                }
                else if (checkType.Equals("4"))//承诺函
                {
                    if (CNType.Contains(headCode))
                        return true;
                    else
                        return false;
                }
                else if (checkType.Equals("5"))//零星
                {
                    if (imageCode.Length == 19)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                WriteLog(ex);
                return false;
            }
            #endregion
        }

        /// <summary>
        /// 复制数据到剪切板
        /// </summary>
        /// <param name="list"></param>
        public static void ClipboardFunction(ListView list)
        {
            try
            {
                string groupStr = "";
                IList listBox = list.SelectedItems;
                foreach (SucceseListModel group in listBox)
                {
                    groupStr = group.Group;
                }
                Clipboard.SetDataObject(groupStr);
                ShowMsgFrom("内容:[" + groupStr + "]已经复制到剪贴板");
            }
            catch (System.Exception ex)
            {
                WriteLog(ex);
                return;
            }
        }

        public static string getChiFromEvaResult(int value)
        {
            #region
            string _scanType = "";
            switch (value)
            {
                case 1:
                    _scanType = "[仅删除]";
                    break;
                case 2:
                    _scanType = "[仅补扫]";
                    break;
                case 4:
                    _scanType = "[删补影像]";
                    break;
                case 5:
                    _scanType = "[删补纸质]";
                    break;
                default:
                    _scanType = "";
                    break;
            }
            return _scanType;
            #endregion
        }
        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public static String File2Bytes(string path)
        {
            #region
            try
            {
                Bitmap bmp = new Bitmap(path);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                return strbaser64;
            }
            catch (Exception ex)
            {
                WriteLog(ex);
                MessageBox.Show("ImgToBase64String 转换失败\nException:" + ex.Message);
                return "";
            }
            #endregion
        }

        /// <summary>
        /// 图片转Base64编码
        /// </summary>
        /// <param name="txtFileName"></param>
        public static void Base64StringToImage(string txtFileName)
        {
            #region
            try
            {
                FileStream ifs = new FileStream(txtFileName, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(ifs);

                String inputStr = sr.ReadToEnd();
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                //bmp.Save(txtFileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Close();
                sr.Close();
                ifs.Close();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show("Base64StringToImage 转换失败\nException：" + ex.Message);
            }
            #endregion
        }

        /// <summary>
        /// 解码密码
        /// </summary>
        public static string DecodeBase64(string code)
        {
            byte[] inArray = Convert.FromBase64String(code);
            string decode = System.Text.Encoding.UTF8.GetString(inArray);
            return decode;
        }

        #region 释放内存
        [System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>
        /// 释放内存
        /// </summary>
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
        #endregion 

        /// <summary>
        /// 图像切割
        /// </summary>
        /// <param name="url">图像文件名称</param>
        /// <param name="width">切割后图像宽度</param>
        /// <param name="height">切割后图像高度</param>
        /// <param name="savePath">切割后图像文件保存路径</param>
        /// <param name="fileExt">切割后图像文件扩展名</param>
        public static void CutImage(string url, int width, int height, string savePath, string fileExt)
        {
            #region
            try
            {
                Bitmap bitmap = new Bitmap(url);
                width = bitmap.Width;
                height = bitmap.Height / 2;
                Decimal MaxRow = Math.Ceiling((Decimal)bitmap.Height / height);   //计算能分割多少行
                Decimal MaxColumn = Math.Ceiling((decimal)bitmap.Width / width);  //计算能分割多少列
                for (decimal i = 0; i < MaxRow; i++)
                {
                    for (decimal j = 0; j < MaxColumn; j++)
                    {
                        string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + i.ToString() + "-" + j.ToString() + "." + fileExt;
                        Bitmap bmp = new Bitmap(width, height);

                        for (int offsetX = 0; offsetX < width; offsetX++)
                        {
                            for (int offsetY = 0; offsetY < height; offsetY++)
                            {
                                if (((j * width + offsetX) < bitmap.Width) && ((i * height + offsetY) < bitmap.Height))
                                {
                                    bmp.SetPixel(offsetX, offsetY, bitmap.GetPixel((int)(j * width + offsetX), (int)(i * height + offsetY)));
                                }
                            }
                        }
                        Graphics g = Graphics.FromImage(bmp);
                        //g.DrawString("哲慧科技", new Font("黑体", 20), new SolidBrush(Color.FromArgb(70, Color.WhiteSmoke)), 60, height / 2);//加水印
                        ImageFormat format = ImageFormat.Png;
                        switch (fileExt.ToLower())
                        {
                            case "png":
                                format = ImageFormat.Png;
                                break;
                            case "bmp":
                                format = ImageFormat.Bmp;
                                break;
                            case "gif":
                                format = ImageFormat.Gif;
                                break;
                        }
                        bmp.Save(savePath + "//" + filename, format);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        /// <summary>
        /// 保存图片到缓存路径，主要是针对扫描进来的图像
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="strFilePath"></param>
        public static void SaveImage(BitmapSource bitmap, String strFilePath)
        {
            BitmapEncoder encoder = null;
            encoder = new JpegBitmapEncoder();

            FileStream destStream = new FileStream(strFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(destStream);
            destStream.Close();
        }

        /// <summary>
        /// 获取用户缓存信息
        /// </summary>
        /// <returns></returns>
        public static string readUserInfo()
        {
            #region
            Dictionary<string, LoginData> users;
            string account = "";
            string filePath = "C:/MssClientCache/";//缓存保存地址
            if (!Directory.Exists(filePath))//判断文件夹是否存在 
            {
                return "";//不存在就不执行下面
            }
            FileStream fs = new FileStream("C:/MssClientCache/userData.bin", FileMode.OpenOrCreate);
            if (fs.Length > 0)
            {
                BinaryFormatter bf = new BinaryFormatter();
                //读出存在Data.bin 里的用户信息
                users = bf.Deserialize(fs) as Dictionary<string, LoginData>;

                //循环添加到Combox1
                foreach (LoginData user in users.Values)
                {
                    account = user.LoginName;
                    break;
                }
            }
            fs.Close();
            return account;
            #endregion
        }

        private static string GetIds(IList<TreeModel> treeList)
        {
            StringBuilder ids = new StringBuilder();

            foreach (TreeModel tree in treeList)
            {
                ids.Append(tree.Id).Append(",");
            }
            return ids.ToString();
        }

        private static string GetNames(IList<TreeModel> treeList)
        {
            StringBuilder ids = new StringBuilder();

            foreach (TreeModel tree in treeList)
            {
                ids.Append(tree.Name).Append(",");
            }
            return ids.ToString();
        }

        /// <summary>
        /// bitmap to image
        /// </summary>
        /// <param name="Bi"></param>
        /// <returns></returns>
        private static System.Windows.Controls.Image Bitmap2Image(System.Drawing.Bitmap Bi)
        {
            #region
            MemoryStream ms = new MemoryStream();
            Bi.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            BitmapImage bImage = new BitmapImage();
            bImage.BeginInit();
            bImage.StreamSource = new MemoryStream(ms.ToArray());
            bImage.EndInit();
            ms.Dispose();
            Bi.Dispose();
            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
            img.Source = bImage;
            return img;
            #endregion
        }

        /// <summary>
        /// 图像切割
        /// </summary>
        /// <param name="url">图像文件名称</param>
        /// <param name="width">切割后图像宽度</param>
        /// <param name="height">切割后图像高度</param>
        /// <param name="savePath">切割后图像文件保存路径</param>
        /// <param name="fileExt">切割后图像文件扩展名</param>
        public static void CutToReadBarcode(string url, int width, int height, string savePath, string fileExt)
        {
            #region
            Bitmap bitmap = new Bitmap(url);
            width = bitmap.Width;
            height = bitmap.Height / 2;
            Decimal MaxRow = Math.Ceiling((Decimal)bitmap.Height / height);   //计算能分割多少行
            Decimal MaxColumn = Math.Ceiling((Decimal)bitmap.Width / width);  //计算能分割多少列
            for (decimal i = 0; i < MaxRow; i++)
            {
                for (decimal j = 0; j < MaxColumn; j++)
                {
                    string filename = i.ToString() + "," + j.ToString() + "." + fileExt;
                    Bitmap bmp = new Bitmap(width, height);

                    for (int offsetX = 0; offsetX < width; offsetX++)
                    {
                        for (int offsetY = 0; offsetY < height; offsetY++)
                        {
                            if (((j * width + offsetX) < bitmap.Width) && ((i * height + offsetY) < bitmap.Height))
                            {
                                bmp.SetPixel(offsetX, offsetY, bitmap.GetPixel((int)(j * width + offsetX), (int)(i * height + offsetY)));
                            }
                        }
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 处理图片灰度
        /// </summary>
        /// <param name="original"></param>
        /// <returns></returns>
        public static Bitmap MakeGrayscale3(Bitmap original)
        {
            #region
            //create a blank bitmap the same size as original
            Bitmap newBitmap;
            try
            {
                double Width = original.Width * 1;
                double Height = original.Height * 1;
                int WidthInt = (int)Width;
                int HeightInt = (int)Height;
                newBitmap = new Bitmap(WidthInt, HeightInt);
                //get a graphics object from the new image
                Graphics g = Graphics.FromImage(newBitmap);

                //create the grayscale ColorMatrix
                System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(
                   new float[][]
                   {
                        new float[] {.3f, .3f, .3f, 0, 0},
                        new float[] {.59f, .59f, .59f, 0, 0},
                        new float[] {.11f, .11f, .11f, 0, 0},
                        new float[] {0, 0, 0, 1, 0},
                        new float[] {0, 0, 0, 0, 1}
                   });

                //create some image attributes
                ImageAttributes attributes = new ImageAttributes();

                //set the color matrix attribute
                attributes.SetColorMatrix(colorMatrix);

                //draw the original image on the new image
                //using the grayscale color matrix
                g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                   0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
                CommonUtil.ClearMemory();
                //dispose the Graphics object
                g.Dispose();
            }
            catch (Exception ex)
            {
                CommonUtil.ClearMemory();
                CommonUtil.WriteLog(ex);
                return original;
            }
            return newBitmap;
            #endregion
        }

        /// <summary>
        /// Login 登录post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string LoginPost(string url, Dictionary<string, string> dic)
        {
            #region
            string result = "";
            HttpWebRequest req;
            System.GC.Collect();
            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                req.Method = "POST";
                req.Timeout = 60000;
                req.Proxy = null;
                //req.UserAgent = "MSIE; Windows NT 5.1; Windows NT 6.0";
                req.KeepAlive = false;
                System.Net.ServicePointManager.DefaultConnectionLimit = 150;
                req.ContentType = "application/x-www-form-urlencoded";

                //封装参数 -s
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                //封装参数 -e

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
            }
            catch (NotSupportedException ex)
            {
                CommonUtil.WriteLog(ex);
                return "netError";
            }
            catch (WebException ex)
            {
                CommonUtil.WriteLog(ex);
                return "netError";
            }
            catch (UriFormatException ex)
            {
                CommonUtil.WriteLog(ex);
                return "urlError";
            }
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return "";
            }
            return result;
            #endregion
        }

        /// <summary>
        /// 获取当前客户端连接的服务环境
        /// </summary>
        /// <returns></returns>
        public static string getSysTypeCode()
        {
            String SysTypeCode = "";
            UpGradeModel upGradeModel = CommonUtil.getSysProperty("SysTypeCode");
            if (null != upGradeModel)
                SysTypeCode = upGradeModel.value;

            return SysTypeCode;
        }

        public static UpGradeModel getSysProperty(string key)
        {
            Dictionary<string, string> paramsDic = new Dictionary<string, string>();
            paramsDic.Add("key", key);
            paramsDic.Add("account", "123");
            paramsDic.Add("password", "123");
            paramsDic.Add("func", "keyInfo");
            UpGradeModel versionModel = new UpGradeModel();
            String strResult1 = "";
            if (key.Equals("New_Version"))
                strResult1 = CommonUtil.LoginPost(Global.getInstance().strUrl + Global.getInstance().strNewVersion, paramsDic);
            else
                strResult1 = CommonUtil.LoginPost(Global.getInstance().strUrl + Global.getInstance().strOCRTrigger, paramsDic);

            if (strResult1.Equals("")) return null;
            var ms1 = new MemoryStream(Encoding.UTF8.GetBytes(strResult1));
            {
                DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(UpGradeModel));
                versionModel = (UpGradeModel)deseralizer.ReadObject(ms1);// //反序列化ReadObject
            }
            return versionModel;
        }

        /// <summary>
        /// 主窗口 MSSWindow 对接java服务端post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string MssPost(string url, Dictionary<string, string> dic)
        {
            #region
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.Timeout = 120000;
                req.ReadWriteTimeout = 120000;
                req.ContentType = "application/x-www-form-urlencoded";

                #region 添加Post 参数  
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;

                #endregion

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();

                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show(ex.Message);
                return "error";
            }
            return result;
            #endregion
        }

        /// <summary>
        /// 更新客户端post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static String clientPost(string url, Dictionary<string, string> dic)
        {
            #region
            HttpWebRequest req;
            string result = "";
            MemoryStream stream2;
            string tag = "0";
            try
            {
                req = (HttpWebRequest)WebRequest.Create(new Uri(url));
                System.Net.ServicePointManager.DefaultConnectionLimit = 20;
                req.Method = "POST";
                req.Timeout = 120000;
                req.Proxy = null;
                req.KeepAlive = true;
                req.ContentType = "application/x-www-form-urlencoded";
                //封装参数 ---start
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                //封装参数 ---end

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    Console.WriteLine("reqStream：" + reqStream.ToString());
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                System.GC.Collect();
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream streamReader = resp.GetResponseStream();
                Console.WriteLine("streamReader：" + streamReader.ToString());
                //获取响应内容  
                using (StreamReader reader = new StreamReader(streamReader, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    byte[] array = Encoding.GetEncoding("iso-8859-1").GetBytes(result);
                    stream2 = new MemoryStream(array);
                    Console.WriteLine("stream2：" + stream2.ToString());
                }
                string filePath = @"C:\MssClientUpGrade";
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = stream2.Read(buffer, 0, bufferSize);
                if (!Directory.Exists(filePath))//判断文件夹是否存在 filePath为文件保存的路径
                    Directory.CreateDirectory(filePath);//不存在则创建文件夹
                FileStream outputStream = new FileStream(filePath + "/" + "setup.exe", FileMode.CreateNew);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = stream2.Read(buffer, 0, bufferSize);
                }
                stream2.Close();
                outputStream.Close();
                tag = "1";
                return tag;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                MessageBox.Show(ex.Message, "提示信息");
                return tag;
            }
            #endregion
        }


        /// <summary>
        /// 调用应用的服务来上传图像
        /// </summary>
        /// <param name="fileInfo">本地的图像文件信息</param>
        /// <param name="fileHeardName">文件名</param>
        /// <param name="functionType">上传对应的接口方法</param>
        /// <param name="imagecode">imagecode</param>
        /// <param name="imageType">imageType</param>
        /// <param name="bizId"></param>
        public static void uploadImageByWeb(FileInfo fileInfo, string fileHeardName, string functionType, string imagecode, string imageType, string username)
        {
            Dictionary<string, string> imageDic = new Dictionary<string, string>();
            string picStr = CommonUtil.File2Bytes(fileInfo.FullName);//图像转换为base64编码
            imageDic.Add("password", "password");
            imageDic.Add("account", username);
            imageDic.Add("fileNameStr", fileHeardName + fileInfo.Name);
            imageDic.Add("functionType", functionType);//uploadOCR,uploadImageByWeb
            imageDic.Add("image_code", imagecode);
            imageDic.Add("bizType", imageType);
            imageDic.Add("imageId", picStr);//图像的base64编码
            CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, imageDic);
        }


        /// <summary>
        /// 上传时获取ftp信息
        /// </summary>
        /// <param name="groupItem"></param>
        /// <returns></returns>
        public static LoginData GetFtpData(GroupModel groupItem)
        {
            Dictionary<string, string> ftpSync = new Dictionary<string, string>();

            //设置ftp数据：根据单号，类型获取对应组织，在获取对应的ftp信息
            ftpSync.Add("password", "password");
            ftpSync.Add("account", "account");
            ftpSync.Add("functionType", "getFtpInfo");
            if (groupItem.isBuSaoTag.Equals(1))
                ftpSync.Add("image_code", groupItem.reqCode);
            else
                ftpSync.Add("image_code", groupItem.ImageCode);

            ftpSync.Add("bizType", groupItem.type);
            ftpSync.Add("imageId", "");
            ftpSync.Add("bizId", "");
            string ftpInfo = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, ftpSync);
            LoginData ftpData = new LoginData();
            //获取ftp信息
            var ftpMs = new MemoryStream(Encoding.UTF8.GetBytes(ftpInfo));
            {
                DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(LoginData));
                ftpData = (LoginData)deseralizer.ReadObject(ftpMs);// //反序列化ReadObject
            }
            return ftpData;
        }

        /// <summary>
        /// 获取ftp上传信息
        /// </summary>
        /// <param name="groupItem"></param>
        /// <returns></returns>
        public static CanUploadData GetFtpUploadPath(GroupModel groupItem)
        {
            Dictionary<string, string> paramsDic = new Dictionary<string, string>();
            paramsDic.Add("ticketId", Global.getInstance().loginData.data.ticketId);
            paramsDic.Add("imageType", groupItem.type);
            CanUploadData model = new CanUploadData();
            //判断补单中的删除，添加这两种状态，如果不是这两种状态就return
            if (groupItem.isBuSaoTag.Equals(1))
            {
                paramsDic.Add("imageCode", groupItem.reqCode);
                paramsDic.Add("buDanNodeType", "1");
            }
            else
            {
                paramsDic.Add("imageCode", groupItem.ImageCode);
                paramsDic.Add("buDanNodeType", "0");
            }
            //获取ftp上传路径信息
            String strResult = CommonUtil.MssPost(Global.getInstance().strUrl + Global.getInstance().strCanUpload, paramsDic);
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(strResult));
            {
                DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(CanUploadData));
                model = (CanUploadData)deseralizer.ReadObject(ms);// //反序列化ReadObject
            }
            return model;
        }

        public static Boolean GetOCRNeedUpload(String imageCode)
        {
            Boolean stute = false;
            try
            {
                Dictionary<string, string> imageDic = new Dictionary<string, string>();
                //获取是否需要上传到OCR服务器的Tag-OCRNeedUpload，0-不需要，1-需要
                imageDic.Add("password", "password");
                imageDic.Add("account", "account");
                imageDic.Add("functionType", "OCRCanUploadTag");
                imageDic.Add("image_code", imageCode);
                imageDic.Add("bizType", "0");
                imageDic.Add("imageId", "0");
                imageDic.Add("bizId", "0");
                CanUploadData modelOCR = null;

                string strResultOCR = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, imageDic);
                var msOCR = new MemoryStream(Encoding.UTF8.GetBytes(strResultOCR));
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(CanUploadData));
                    modelOCR = (CanUploadData)deseralizer.ReadObject(msOCR);// //反序列化ReadObject
                }
                if (null != modelOCR && ("1".Equals(modelOCR.message) || "2".Equals(modelOCR.message) || "12".Equals(modelOCR.message)))
                    stute = true;
            }
            catch (Exception ex )
            {
                WriteLog(ex);
            }

            return stute;
        }

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_ConnectUsbPort(string portName, int readTimeOut);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_OpenPrinter(string portName);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_ClosePrinter();
        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_SendBuffer(string data);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_AddImageToLabelEx(string imgFilePath, int posX, int posY, int dir, int align);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_AddBarcodeToLabel(string codeToPrint, string codeType, int height,int posX, int posY, int dir, int align, int enlargeWidth);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_SetMediaWidth(int width);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_SetMediaLength(int Length);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_WriteConfig();

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_SetMediaType(int mtype);

        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_SetMediaMarginX(int Margin);
        
        [DllImport("HoneywellPrint.dll")]
        static extern int PRN_PrintLabel(int PrintCount);

        //直接打印 DP指令
        public static void PrintTest_Cmd(String path)
        {
            //Test for send cmd buffer
            if (PRN_OpenPrinter("Honeywell PC42t (203 dpi) - DP (副本 1)") == 0)
            {
                //String prnCmd = "nasc 1\n nascd \"\"\n PRPOS 50,10\n FONT\"Swiss 721 BT\",10\n PT \"Honey Test\"\n PF\n";
                //String prnCmd = "PP 150.150\n " +
                //    //"PT \"Honeywell-PC42d\" \n " +
                //    "BARSET \"CODE39\",3,1,2,100" +
                //    "ALIGN 2" +
                //    "BARFONT \"Univers\",10,8,5,1,1,100 ON \n" +
                //    "BF ON \n" +
                //    "PB\"TYA25540000000818110080093TY1\" \n" +
                //    "PF\"";
                //PRN_SendBuffer(prnCmd);
                int ret = 0;
                PRN_SetMediaType(1);
                ret = PRN_AddImageToLabelEx(path, 20, 20, 1,1);
                ret = PRN_PrintLabel(1);
            }
            PRN_ClosePrinter();
        }

        /// <summary>
        /// Bitmap转换为BitmapImage
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static BitmapImage BitmapToBitmapImageFromBitmap(Bitmap bitmap)
        {
            #region
            BitmapImage bitmapImage = new BitmapImage();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = new MemoryStream(ms.ToArray());
                bitmapImage.EndInit();
            }
            ClearMemory();
            return bitmapImage;
            #endregion
        }

        /// <summary>
        ///  获取是否有补单任务
        /// </summary>
        public static string buDanPost(string url, Dictionary<string, string> dic)
        {
            #region
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Timeout = 25000;

                #region 添加Post 参数  
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;

                #endregion

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return "";
            }
            return result;
            #endregion
        }

        /// <summary>  
        /// 将异常打印到LOG文件  
        /// </summary>  
        /// <param name="ex">异常</param>  
        /// <param name="LogAddress">日志文件地址</param>  
        public static void WriteLog(Exception ex)
        {
            #region
            lock (writerLogLocker)
            {
                string logPath = @"C:\MssClientCache\log\";
                //如果日志文件为空，则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件  
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
                String LogAddress = @"C:\MssClientCache\log\" +
                            DateTime.Now.Year + '-' +
                            DateTime.Now.Month + '-' +
                            DateTime.Now.Day + "_" + readUserInfo() + "_Log.txt";

                //把异常信息输出到文件
                StreamWriter fs = new StreamWriter(LogAddress, true);
                fs.WriteLine("当前时间：" + DateTime.Now.ToString());
                fs.WriteLine("异常信息：" + ex.Message);
                fs.WriteLine("异常对象：" + ex.Source);
                fs.WriteLine("调用堆栈：\n" + ex.StackTrace.Trim());
                fs.WriteLine("触发方法：" + ex.TargetSite);
                fs.WriteLine();
                fs.Close();
            }
            #endregion
        }

        /// <summary>
        /// 记录自己定义的日志
        /// </summary>
        /// <param name="msg">记录信息</param>
        /// <param name="function">对应方法名称</param>
        public static void WriteLogStr(String msg, String function)
        {
            #region
            lock (writerLogLocker)
            {
                string logPath = @"C:\MssClientCache\log\";
                //如果日志文件为空，则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件  
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
                String LogAddress = @"C:\MssClientCache\log\" +
                            DateTime.Now.Year + '-' +
                            DateTime.Now.Month + '-' +
                            DateTime.Now.Day + "_" + readUserInfo() + "_Log.txt";

            
                //把异常信息输出到文件
                StreamWriter fs = new StreamWriter(LogAddress, true);
                fs.WriteLine("当前时间：" + DateTime.Now.ToString());
                fs.WriteLine("异常信息：" + msg);
                fs.WriteLine("触发方法：" + function);
                fs.WriteLine();
                fs.Close();
            }
            #endregion
        }

        /// <summary>
        /// 记录自己定义的日志
        /// </summary>
        /// <param name="msg">记录ftp上传信息</param>
        /// <param name="function">对应方法名称</param>
        public static void WriteFtpLog(String msg, String function)
        {
            #region
            string logPath = @"C:\MssClientCache\log\";
            //如果日志文件为空，则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件  
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            String LogAddress = @"C:\MssClientCache\log\" +
                        DateTime.Now.Year + '-' +
                        DateTime.Now.Month + '-' +
                        DateTime.Now.Day + "_" + readUserInfo() + "_FTPLog.txt";

            //把异常信息输出到文件
            StreamWriter fs = new StreamWriter(LogAddress, true);
            fs.WriteLine("当前时间：" + DateTime.Now.ToString());
            fs.WriteLine("异常信息：" + msg);
            fs.WriteLine("触发方法：" + function);
            fs.WriteLine();
            fs.Close();
            #endregion
        }

        /// <summary>
        /// 合并图像
        /// </summary>
        /// <param name="exchange">交换，1-y,0-n</param>
        /// <param name="UpAndDown">上下，1-y,0-n</param>
        /// <param name="letfAndRight">左右,1-y,0-n</param>
        /// <returns>path，保存的图像地址</returns>
        public static String MergeImage(int exchange, int UpAndDown, int letfAndRight, String url1, String url2)
        {
            #region
            Bitmap bmp = new Bitmap(10, 10);
            Bitmap img1 = new Bitmap(url1);
            Bitmap img2 = new Bitmap(url2);
            if (exchange.Equals(1))//交换图像
            {
                Bitmap temp = img1;
                img1 = img2;
                img2 = temp;
            }
            if (UpAndDown.Equals(1))//上下排列
            {
                if (img1.Width > img2.Width)//确定以哪张图像的宽度做合并的新图像的宽度
                {
                    bmp = new Bitmap(img1.Width, img1.Height + img2.Height);
                }
                else
                {
                    bmp = new Bitmap(img2.Width, img1.Height + img2.Height);
                }
            }
            if (letfAndRight.Equals(1))//左右排列
            {
                if (img1.Height > img2.Height) //确定以哪张图像的高度做合并的新图像的高度
                {
                    bmp = new Bitmap(img1.Width + img2.Width, img1.Height);
                }
                else
                {
                    bmp = new Bitmap(img1.Width + img2.Width, img2.Height);
                }
            }

            Graphics g = Graphics.FromImage(bmp);
            g.Clear(System.Drawing.Color.White);
            if (UpAndDown.Equals(1))
            {
                g.DrawImage(img1, 0, 0, img1.Width, img1.Height);
                g.DrawImage(img2, 0, img1.Height, img2.Width, img2.Height);
            }
            if (letfAndRight.Equals(1))
            {
                g.DrawImage(img1, 0, 0, img1.Width, img1.Height);
                g.DrawImage(img2, img1.Width, 0, img2.Width, img2.Height);
            }
            GC.Collect();
            String imageUrl = @"C:\MssClientCache\Scannned\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
            SaveScanImgae(bmp,imageUrl,70);
            //bmp.Save(imageUrl);
            ClearMemory();
            return imageUrl;
            #endregion
        }

        /// <summary>
        /// 清除缓存的图像
        /// </summary>
        /// <param name="closeType">是否是关闭客户端时，true-是，false-不是</param>
        /// <param name="showInfo">是否显示清理信息,0-不显示，1-显示</param>
        public static void clearCache(bool closeType, int showInfo)
        {
            #region
            String path = @"C:\MssClientCache\Scannned";     //扫描图像缓存
            String path1 = @"C:\MssClientCache\imageCache";  //补单图像缓存
            String path2 = @"C:\MssClientCache\QrCache";     //ocr识别缓存
            long len1 = 0;
            long len2 = 0;
            long len3 = 0;
            try
            {
                DirectoryInfo dir  = new DirectoryInfo(path);
                DirectoryInfo dir1 = new DirectoryInfo(path1);
                DirectoryInfo dir2 = new DirectoryInfo(path2);
                FileSystemInfo[] fileinfo  = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                FileSystemInfo[] fileinfo1 = dir1.GetFileSystemInfos();  
                FileSystemInfo[] fileinfo2 = dir2.GetFileSystemInfos();  

                foreach (FileInfo fi in dir.GetFiles())
                    len1 += fi.Length;
                foreach (FileInfo fi in dir1.GetFiles())
                    len2 += fi.Length;
                foreach (FileInfo fi in dir2.GetFiles())
                    len3 += fi.Length;

                if (closeType)
                {
                    foreach (FileSystemInfo i in fileinfo)
                    {
                        if (i is DirectoryInfo)            //判断是否文件夹
                        {
                            DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                            subdir.Delete(true);          //删除子目录和文件
                        }
                        else
                            File.Delete(i.FullName);      //删除指定文件
                    }

                    foreach (FileSystemInfo i in fileinfo1)
                    {

                        if (i is DirectoryInfo)            //判断是否文件夹
                        {
                            DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                            subdir.Delete(true);          //删除子目录和文件
                        }
                        else
                            File.Delete(i.FullName);      //删除指定文件
                    }
                }

                foreach (FileSystemInfo i in fileinfo2)
                {

                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                        File.Delete(i.FullName);      //删除指定文件
                }

                if (showInfo.Equals(1))
                    ShowMsgFrom("清除完成，共清理：" + (((len1 + len2 + len3) / 1024) / 1024) + "MB");
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        /// <summary>
        /// bitmap转换为bitmapImage
        /// </summary>
        /// <param name="imagePath">图像地址</param>
        /// <returns></returns>
        public static BitmapImage Bitmap2BitmapImageFromImagrPath(String imagePath)
        {
            #region
            BitmapImage bim = new BitmapImage();
            FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using (BinaryReader loader = new BinaryReader(fs))
            {
                FileInfo fd = new FileInfo(imagePath);
                int Length = (int)fd.Length;
                byte[] buf = new byte[Length];
                buf = loader.ReadBytes((int)fd.Length);
                loader.Dispose();
                loader.Close();
                bim.BeginInit();
                bim.StreamSource = new MemoryStream(buf);
                bim.EndInit();
                bim.Freeze();
            }
            ClearMemory();
            return bim;
            #endregion
        }

        /// <summary>
        /// bitmap转换为bitmapImage
        /// </summary>
        /// <param name="imagePath">图像地址</param>
        /// <returns></returns>
        public static BitmapImage Bitmap2BitmapImageFromBitmat(Bitmap bitmap)
        {
            #region
            Bitmap bitmapSource = new Bitmap(bitmap.Width, bitmap.Height);
            int i, j;
            for (i = 0; i < bitmap.Width; i++)
                for (j = 0; j < bitmap.Height; j++)
                {
                    Color pixelColor = bitmap.GetPixel(i, j);
                    Color newColor = Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B);
                    bitmapSource.SetPixel(i, j, newColor);
                }
            MemoryStream ms = new MemoryStream();
            bitmapSource.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(ms.ToArray());
            bitmapImage.EndInit();

            return bitmapImage;
            #endregion
        }

        /// <summary>
        /// 图像添加水印
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static Bitmap WaterMarkBitmap(Bitmap img)
        {
            var g = Graphics.FromImage(img);
            //设置画布平滑性
            g.SmoothingMode = SmoothingMode.AntiAlias;
            //填充半透明三角形
            var triggleLeg = (img.Width > img.Height ? img.Height : img.Width) / 3;
            var path = new GraphicsPath();
            path.AddLine(img.Width - triggleLeg, img.Height, img.Width, img.Height - triggleLeg);
            path.AddLine(img.Width, img.Height - triggleLeg, img.Width, img.Height);
            path.AddLine(img.Width, img.Height, img.Width - triggleLeg, img.Height);

            g.FillPath(new SolidBrush(System.Drawing.Color.FromArgb(30, System.Drawing.Color.Gray)), path);
            //将原点移动到三角形斜边的中间位置
            g.TranslateTransform(img.Width - triggleLeg / 2, img.Height - triggleLeg / 2);
            //旋转45度
            g.RotateTransform(-45);
            //Math.Acos返回值是相对PI的值，因此需要转换为度数
            //var angle = Math.Acos(a / Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2))) / Math.PI * 180;
            //g.RotateTransform((float)-angle);
            // 绘制水印文字
            var font = new Font("Microsoft Yahei", 20, System.Drawing.FontStyle.Regular);
            string text = "测试水印的";
            //测量文字长度
            var size = g.MeasureString(text, font);
            //绘制文字时，以文字长度的中间位置为中心，因此绘制的起点为：0-长度/2；并设置高度距离原点半行高
            g.DrawString(text, font, Brushes.Gray, -size.Width / 2, size.Height / 2);
            size = g.MeasureString(DateTime.Now.ToString("yyyy-MM-dd"), font);
            g.DrawString(DateTime.Now.ToString("yyyy-MM-dd"), font, Brushes.Gray, -size.Width / 2, size.Height * 3 / 2);
  
            return img;
        }

        /// <summary>
        /// 获取windows系统版本名称
        /// </summary>
        /// <param name="ver"></param>
        /// <returns></returns>
        public static string GetOsVersion(Version ver)
        {
            string strClient = "";
            if (ver.Major == 5 && ver.Minor == 1)
                strClient = "WinXP";
            else if (ver.Major == 6 && ver.Minor == 0)
                strClient = "WinVista";
            else if (ver.Major == 6 && ver.Minor == 1)
                strClient = "Win7";
            else if (ver.Major == 6 && ver.Minor == 2)
                strClient = "Win10";
            else if (ver.Major == 5 && ver.Minor == 0)
                strClient = "Win2000";
            else strClient = "";
            return strClient;
        }

        public static void WriteableBitmap()
        {
            #region
            //if (m_bDetectWhitePaper)
            //{
            //    //Decline the img resolution.
            //    System.Drawing.Rectangle srcRect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            //    int nDestWidth = 500;
            //    int nDestHeight = bitmap.Height * 500 / bitmap.Width;
            //    System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(0, 0, nDestWidth, nDestHeight);
            //    //Rect destRect = new Rect(new Size(nDestWidth, nDestHeight));
            //    Bitmap bitDest = new Bitmap(nDestWidth, nDestHeight);
            //    Graphics gs = Graphics.FromImage(bitDest);
            //    gs.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
            //    gs.Dispose();

            //    //Judge the img whether is a blank.
            //    Boolean bBlank = false;
            //    System.Drawing.Color c;
            //    int width = bitDest.Width;
            //    int height = bitDest.Height;
            //    long nCount = 0;
            //    for (int i = 0; i < height; i++)
            //    {
            //        for (int j = 0; j < width; j++)
            //        {
            //            c = bitDest.GetPixel(j, i);
            //            int r = c.R;
            //            int g = c.G;
            //            int b = c.B;
            //            if ((r + g + b) / 3 < 100)
            //            {
            //                //bitImage.SetPixel(j, i, System.Drawing.Color.FromArgb(0, 0, 0));
            //                nCount++;
            //            }
            //        }
            //    }

            //    //MessageBox.Show(nCount.ToString());

            //    //It is a blank img and return.
            //    if (20 > nCount) //less than 20 black points
            //    {
            //        bBlank = true;
            //        m_bBarcode = false;
            //        m_strBarcode = "";
            //        Gdi32Native.DeleteObject(hbitmap);
            //        return;
            //    }
            //}
            #endregion
        }

        /// <summary>
        /// 把object转换为json格式的字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string formatJson(Object obj)
        {
            #region
            string strParam = "";
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(List<ImagesData>));
            MemoryStream msObj = new MemoryStream();
            js.WriteObject(msObj, obj);
            msObj.Position = 0;
            StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
            strParam = sr.ReadToEnd();
            sr.Close();
            msObj.Close();
            return strParam;
            #endregion
        }

        /// <summary>
        /// openCV处理识别图像中是否含有条形码，逻辑：识别提取图像中的矩形区域，
        /// 按照规定的比例范围来判断是否存在条形码
        /// </summary>
        /// <param name="path">图像路径</param>
        /// <returns></returns>
        public static bool detectImage(String path,string dic)
        {
            #region
            Mat textImageSrc = Cv2.ImRead(path);
            Bitmap bitmap = new Bitmap(path);
            if (!Directory.Exists("E:\\OenpCVImage\\"+dic))//判断文件夹是否存在 
            {
                Directory.CreateDirectory("E:\\OenpCVImage\\" + dic);//不存在则创建文件夹 
            }

            //Cv2.ImShow("imgDrawRect4.jpg", textImageSrc);
            //1.转化成灰度图
            Mat gray = new Mat();
            Cv2.CvtColor(textImageSrc, gray, ColorConversionCodes.RGB2GRAY);

            //2.形态学变换的预处理，得到可以查找矩形的轮廓
            string fileFrontName = DateTime.Now.ToString("yyyyMMddHHmmssf");
            Mat dilation = CommonUtil.preprocess(gray, dic, fileFrontName);

            //3.查找和筛选文字区域
            IList<RotatedRect> rects = CommonUtil.FindTextRegion(dilation);
            //4.用绿线画出这些找到的轮廓
            Scalar scalar = new Scalar(0, 255, 0);
            foreach (RotatedRect rect in rects)
            {
                //Rectangle CropArea = new Rectangle(rect.Points(),rect.Size);
                Point2f[] P;
                P = rect.Points();
                for (int j = 0; j <= 3; j++)
                {
                    //Cv2.Line(textImageSrc, P[j], P[(j + 1) % 4], scalar, 2);
                }
                
                //OcrResult ocr = Ocr.Read(bitmap, rect);
                //Console.WriteLine(ocr.Text);
            }
            textImageSrc.SaveImage("E:\\OenpCVImage\\" + dic +"\\"+ fileFrontName + "_8-标识图.jpg");
            textImageSrc.SaveImage("E:\\OenpCVImage\\" + fileFrontName + "_8-标识图.jpg");
            if (rects.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
            //return true;
            //5.显示带轮廓的图像
            //Cv2.ImShow("img", textImageSrc);
            //Cv2.ImWrite("8-轮廓图.jpg", textImageSrc);
            #endregion
        }


        /// <summary>
        /// 形态学变换的预处理，得到可以查找矩形的轮廓
        /// </summary>
        /// <param name="gray"></param>
        /// <returns></returns>
        public static Mat preprocess(Mat gray, string dic, string fileFrontName)
        {
            #region
            //Sobel算子，x方向求梯度
            Mat matX = new Mat();
            //膨胀和腐蚀操作核参数设定
            //控制高度设置可以控制上下行的膨胀程度，例如3比4的区分能力更强,但也会造成漏检
            Mat elementBF = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5));
            Mat elementBF2 = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(2, 2));
            Cv2.Sobel(gray, matX, MatType.CV_8U, 1, 0, 3, 3, 1, 0);
            //Sobel算子，y方向求梯度
            Mat matY = new Mat();
            Cv2.Sobel(gray, matY, MatType.CV_8U, 0, 1, 3, 3, 1, 0);
            Mat gradXY = new Mat();
            Cv2.Add(matX, matY, gradXY);//XY梯度相加
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_1-XY梯度.jpg", gradXY);

            //模糊 平均模糊
            OpenCvSharp.Size blurSize = new OpenCvSharp.Size(9, 9);
            Mat blurMat = new Mat();
            Cv2.Blur(gradXY, blurMat, blurSize);
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_2-模糊[平均模糊].jpg", blurMat);

            //二值化
            Mat thresholdMat = new Mat();
            Cv2.Threshold(blurMat, thresholdMat, 0, 255, ThresholdTypes.Otsu);
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_3-二值化.jpg", thresholdMat);

            ////开运算
            //Mat morphologyExMat = new Mat();
            //Mat element = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(10, 10));
            //Cv2.MorphologyEx(thresholdMat, morphologyExMat, MorphTypes.Open, element);
            //Cv2.ImWrite("4-开运算.jpg", morphologyExMat);

            //腐蚀一次，去掉细节，表格线等。这里去掉的是竖直的线
            Mat erodeMat = new Mat();
            Cv2.Erode(thresholdMat, erodeMat, elementBF);
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_5-腐蚀1.jpg", erodeMat);

            //Cv2.Erode(erodeMat, erodeMat, elementBF);
            //Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_5-腐蚀2.jpg", erodeMat);

            //膨胀一次，让轮廓突出
            Mat dilateMat = new Mat();
            Cv2.Dilate(erodeMat, dilateMat, elementBF);
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_6-膨胀1.jpg", dilateMat);

            //再膨胀一次，让轮廓突出
            Mat dilateMat2 = new Mat();
            Cv2.Dilate(dilateMat, dilateMat2, elementBF);
            Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_6-膨胀2.jpg", dilateMat2);

            //Cv2.Dilate(dilateMat, dilateMat2, elementBF);
            //Cv2.ImWrite("E:\\OenpCVImage\\" + dic + "\\" + fileFrontName + "_6-膨胀3.jpg", dilateMat2);

            //查找边缘
            //Cv2.Canny(dilateMat2, dilateMat2, 75, 150, 7, true);
            ////Cv2.ImWrite("7-查找边缘.jpg", dilateMat2);
            //Cv2.ImWrite("E:\\OenpCVImage\\" + dic +"\\"+ fileFrontName +"_7-查找边缘.jpg", dilateMat2);

            return dilateMat2;
            #endregion
        }


        public static List<RotatedRect> FindTextRegion(Mat img)
        {
            #region
            List<RotatedRect> rects = new List<RotatedRect>();
            //1.查找轮廓
            int w = img.Width;
            int h = img.Height;
            OpenCvSharp.Point point = new OpenCvSharp.Point(0, 0);
            HierarchyIndex[] hierarchy = null;
            OpenCvSharp.Point[][] contours = null;
            Cv2.FindContours(img, out contours, out hierarchy, RetrievalModes.List, ContourApproximationModes.ApproxNone, new OpenCvSharp.Point(0, 0));
            //contours1 = Cv2.FindContoursAsArray(img,RetrievalModes.CComp, ContourApproximationModes.ApproxSimple);

            //2.筛选那些面积小的
            for (int i = 0; i < contours.Length; i++)
            {
                //找到最小矩形，该矩形可能有方向
                RotatedRect rect = Cv2.MinAreaRect(contours[i]);

                //计算高和宽
                int x = rect.BoundingRect().X;
                int y = rect.BoundingRect().Y;
                float w1 = rect.Size.Width;
                float h1 = rect.Size.Height;

                double matArea = w1 * h1;
                //Console.WriteLine("面积：" + matArea);
                //筛选矩形
                if (matArea >= 60000 && matArea < 200000)
                {
                    Console.WriteLine("--------------分割线----------------");
                    Console.WriteLine("面积：" + matArea);
                    double rate = Math.Round((Math.Min(w1, h1) / Math.Max(w1, h1) * 1.0), 2);//长宽比例
                    Console.WriteLine("长：" + w1 + "宽：" + h1);
                    Console.WriteLine("比例：" + rate);
                    //if ((6.5 <= rate && rate < 7) || (8.8 <= rate && rate < 10))//条形码比例
                    if ( (0.32 <= rate && rate < 0.38) )//发票比例
                    {
                        //Console.WriteLine("长：" + w1 + "宽：" + h1);
                        //Console.WriteLine("面积：" + matArea);
                        Console.WriteLine("合格比例：" + rate);
                        Console.WriteLine("--------------分割线----------------");
                        //符合条件的rect添加到rects集合中
                        rects.Add(rect);
                    }
                }
                //rects.Add(rect);
            }
            return rects;
            #endregion
        }

        public static Bitmap rotateImage(Bitmap b, float angle)
        {
            #region
            //create a new empty bitmap to hold rotated image
            Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(returnBitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            //move rotation point to center of image
            g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
            //rotate
            g.RotateTransform(angle);
            //move image back
            g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
            //draw passed in image onto graphics object
            g.DrawImage(b, new System.Drawing.Point(0, 0));
            return returnBitmap;
            #endregion
        }

        /// <summary>
        /// 保存扫描，导入的图像
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="saveFilePath"></param>
        /// <param name="qualityValue"></param>
        public static void SaveScanImgae(Bitmap bitmap,string saveFilePath,long qualityValue)
        {
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;
            ImageCodecInfo myImageCodecInfo;
            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            myEncoderParameters = new EncoderParameters(1);
            myEncoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityValue);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bitmap.Save(saveFilePath, myImageCodecInfo, myEncoderParameters);
            ClearMemory();
        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        public static byte[] Bitmap2Byte(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }

        public static string getTreeModelNameTag(List<String> nameTagList)
        {
            string nameTag = "";
            foreach (string nt in nameTagList)
                nameTag += nt;
            return nameTag;
        }

        /// <summary>
        /// 根据bitmap的长宽来大概定位dpi是多少，针对A4纸打印尺寸
        /// 101dpi：100+ x 900
        /// 150dpi：1000x1800
        /// 200dpi：1488x2105
        /// 300dpi：2477x3491
        /// 400dpi：3287x4767
        /// 600dpi以上：4000+ x 5000+
        /// </summary>
        /// <param name="bitmap">原图</param>
        /// <returns></returns>
        public static int DeCodeDpiFromBitmap(Bitmap bitmap)
        {
            int DpiTag = 0;//1000
            int width = bitmap.Width;
            int height = bitmap.Height;
            int temp = Math.Max(width, height);
            if (1000 >= temp)
                DpiTag = 101;
            if (2000 >= temp && temp > 1000)
                DpiTag = 150;
            if (3000 >= temp && temp > 2000)
                DpiTag = 200;
            if (4000 >= temp && temp > 3000)
                DpiTag = 300;
            if (5000 >= temp && temp > 4000)
                DpiTag = 400;
            if (5000 < temp)
                DpiTag = 601;
            return DpiTag;
        }

        public static void CreateAppSettingXml(String url)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //创建Xml声明部分，即<?xml version="1.0" encoding="utf-8" ?>
            XmlDeclaration Declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            //创建根节点
            XmlNode rootNode = xmlDoc.CreateElement("appSettings");

            //创建student子节点
            XmlNode testPointNode = xmlDoc.CreateElement("url");
            //创建一个属性
            XmlAttribute testPointID = xmlDoc.CreateAttribute("value");
            testPointID.Value = url;

            //XmlAttribute caseID = xmlDoc.CreateAttribute("CaseId");
            //caseID.Value = "TEST_0001";
            //XmlAttribute name = xmlDoc.CreateAttribute("Name");
            //name.Value = "111";

            ////xml节点附件属性
            testPointNode.Attributes.Append(testPointID);
            //testPointNode.Attributes.Append(caseID);
            //testPointNode.Attributes.Append(name);

            rootNode.AppendChild(testPointNode);

            ////附加根节点
            xmlDoc.AppendChild(rootNode);

            xmlDoc.InsertBefore(Declaration, xmlDoc.DocumentElement);

            //保存Xml文档
            xmlDoc.Save(@"C:\MssClientCache\urlSetting.xml");
        }

        public static List<String> FthPathDecode(String ftpPath)
        {
            List<String> FtpPath = new List<string>();
            
            String[] twoDirList = ftpPath.Split('/');
            string towDir = "";
            if (twoDirList.Length != 1)
                towDir = twoDirList[twoDirList.Length - 1];
            else
            {
                twoDirList = ftpPath.Split('\\');
                towDir = twoDirList[twoDirList.Length - 1];
            }

            if (twoDirList.Length >= 5)
            {
                FtpPath.Add(twoDirList[twoDirList.Length - 1]);
                FtpPath.Add(twoDirList[twoDirList.Length - 2]);
                FtpPath.Add(twoDirList[twoDirList.Length - 3]);
                FtpPath.Add(twoDirList[twoDirList.Length - 4]);

                String RootDir = "";
                for (int i = 0; i < twoDirList.Length - 4; i++)
                {
                    RootDir += twoDirList[i] + "/";
                }

                FtpPath.Add(RootDir);
                FtpPath.Reverse();//反转数组
            }
            else
            {

            }
            return FtpPath;
        }

        public static String getInsertImagesString(IList<TreeModel> treeList)
        {
            String str = "";
            int count = 1;
            foreach (TreeModel t in treeList)
            {
                if (treeList.Count == count)
                {
                    if (t.InsertTag)
                        str += "1";
                    else
                        str += "0";
                }
                else
                {
                    if (t.InsertTag)
                        str += "1,";
                    else
                        str += "0,";
                }
                count++;
            }
            return str;
        }

        public static void SortTreeModelCount(TreeModel treeModel)
        {
            int count = 1;
            foreach (TreeModel grandChild in treeModel.Children)
            {
                grandChild.count = count;
                if (treeModel.isBiSaoType.Equals(1) && !treeModel.Type.Equals("5"))
                    grandChild.Name = treeModel.repImageCode + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                else
                    grandChild.Name = treeModel.imageCode + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                count++;
            }
        }
        //------------------底部分割线---------------------------
    }
}


